<template>
  <div class="content">
    <div class="search">
      <el-form
        :inline="true"
        :model="goodsParams"
        class="demo-form-inline"
      >
        <el-form-item label="状态:">
          <el-select style="width: 160px;" clearable v-model="goodsParams.status" placeholder="请选择">
            <el-option label="未开始" value="pending" />
            <el-option label="进行中" value="processing" />
            <el-option label="已完成" value="completed" />
            <el-option label="已取消" value="cancelled" />
            <el-option label="已结束" value="finished" />
          </el-select>
        </el-form-item>
        <el-form-item label="是否上架:">
          <el-select style="width: 160px;" clearable v-model="goodsParams.listed" placeholder="请选择">
            <el-option label="上架" :value="1" />
            <el-option label="下架" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getSearch">查询</el-button>
          <el-button type="primary" @click="addFn">新增团购</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="table orderTable">
      <el-table
        :data="goodsList"
        height="100%"
        :header-cell-style="{color:'#000' }" 
        border
        style="width: 100%"
        default-expand-all
        empty-text="暂无数据"
        stripe
      >
        <el-table-column type="expand" width="100">
          <template #default="props">
            <div m="4" class="expandTable">
              <div class="stage—search">
                <el-button type="primary" @click="addFnStag(props.row)">新增期</el-button>
              </div>
              <el-table :data="props.row.groupInstances" :border="true" :header-cell-style="{background:'#f1f1f1',color:'#333333'}" :cell-style="{background:'#ffffff'}" empty-text="暂无数据" stripe>
                <el-table-column width="200" label="期" align="center" prop="periodNo" />
                <el-table-column label="拼团开始时间" align="center" prop="startTime" />
                <el-table-column label="拼团结束时间" align="center" prop="endTime" />
                <el-table-column label="取货时间" align="center" prop="pickupTime" />
                <!-- 状态 -->
                <el-table-column width="200" label="状态" align="center" prop="status">
                  <template #default="{ row }">
                    <el-tag v-if="row.status === 'pending'" type="info">未开始</el-tag>
                    <el-tag v-if="row.status === 'processing'" type="success">进行中</el-tag>
                    <el-tag v-if="row.status === 'completed'" type="warning">已完成</el-tag>
                    <el-tag v-if="row.status === 'cancelled'" type="danger">已取消</el-tag>
                    <el-tag v-if="row.status === 'finished'" type="danger">已结束</el-tag>
                  </template>
                </el-table-column>
                <el-table-column fixed="right" label="操作" width="200" align="center">
                  <template #default="{ row }">
                    <el-button type="primary" @click="editFnStag(row)">编辑</el-button>
                  </template>
                </el-table-column>

              </el-table>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="ID" width="120" align="center" prop="group.id" />
        <el-table-column label="商品名称" width="120" align="center" prop="group.title" />
        <el-table-column label="原价" width="120" align="center" prop="group.originalPrice" />
        <el-table-column label="拼团价格" width="120" align="center" prop="group.price" />
        <el-table-column label="商品图片" width="120" align="center">
          <template #default="{ row }">
            <view class="imgs">
              <el-image
                v-for="(item, index) in row.group.imgList"
                :key="index"
                style="width: 50px; height: 50px; margin-right: 10px"
                :src="item"
                :preview-teleported="true"
                :max-scale="7"
                :min-scale="1"
                :preview-src-list="row.group.imgList"
                :initial-index="index"
                fit="cover"
              />
            </view>
          </template>
        </el-table-column>
        <!-- addressImgList -->
        <el-table-column label="地址图片" width="120" align="center">
          <template #default="{ row }">
            <view class="imgs">
              <el-image
                v-for="(item, index) in row.group.addressImgList"
                :key="index"
                style="width: 50px; height: 50px; margin-right: 10px"
                :src="item"
                :preview-teleported="true"
                :max-scale="7"
                :min-scale="1"
                :preview-src-list="row.group.addressImgList"
                :initial-index="index"
                fit="cover"
              />
            </view>
          </template>
        </el-table-column>
        <el-table-column label="描述" width="120" align="center" prop="group.description" />
        <el-table-column label="目标拼团单数" width="120" align="center" prop="group.targetCount" />
        <el-table-column label="库存" align="center" width="120" prop="group.stock" />
        <el-table-column label="取货地址" align="center" width="120" prop="group.address" />
        <el-table-column label="备注" align="center" width="120" prop="group.remark" />
        <el-table-column label="创建时间" align="center" width="120" prop="group.createTime" />
        <el-table-column label="状态" align="center" width="120">
          <template #default="{ row }">
            <el-tag v-if="row.group.listed == 1" type="success">上架</el-tag>
            <el-tag v-else type="danger">下架</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="200" align="center">
          <template #default="{ row }">
            <el-button type="primary" @click="editFn(row)">编辑</el-button>
            <el-button v-if="row.group.listed == 2" type="success" @click="shelves(row)">上架</el-button>
            <el-button v-if="row.group.listed == 1" type="danger" @click="shelves(row)">下架</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-dialog :close-on-click-modal="false" v-model="dialogFormVisible" :title="dialogType=='add'?'新增':'编辑'">
      <el-form ref="ruleFormRef" :model="goodsForm" :rules="rules">
        <el-form-item prop="title" label="商品名称" :label-width="formLabelWidth">
          <el-input v-model="goodsForm.title" autocomplete="off" placeholder=" 请输入商品名称" />
        </el-form-item>
        <el-form-item prop="originalPrice" label="原价" :label-width="formLabelWidth">
          <el-input type="number" v-model="goodsForm.originalPrice" autocomplete="off" placeholder="请输入原价" />
        </el-form-item>
        <el-form-item prop="price" label="拼团价格" :label-width="formLabelWidth">
          <el-input type="number" v-model="goodsForm.price" autocomplete="off" placeholder="请输入拼团价格" />
        </el-form-item>
        <!-- targetCount -->
        <el-form-item prop="targetCount" label="目标拼团单数" :label-width="formLabelWidth">
          <el-input type="number" v-model="goodsForm.targetCount" autocomplete="off" placeholder="请输入目标拼团单数" />
        </el-form-item>
        <el-form-item prop="address" label="取货地址" :label-width="formLabelWidth">
          <el-input v-model="goodsForm.address" autocomplete="off" placeholder="请输入取货地址" />
        </el-form-item>
        <el-form-item prop="listed" label="是否上架" :label-width="formLabelWidth">
          <el-select v-model="goodsForm.listed" placeholder="请选择是否上架">
            <el-option label="上架" value="1" />
            <el-option label="下架" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item prop="description" label="描述" :label-width="formLabelWidth">
          <el-input v-model="goodsForm.description" autocomplete="off" placeholder="请输入描述" />
        </el-form-item>
        <el-form-item prop="remark" label="备注" :label-width="formLabelWidth">
          <el-input v-model="goodsForm.remark" autocomplete="off" placeholder="请输入备注" />
        </el-form-item>
        <el-form-item prop="rank" label="排序" :label-width="formLabelWidth">
          <el-input type="number" v-model="goodsForm.rank" autocomplete="off" placeholder="请输入排序" />
        </el-form-item>
        <el-form-item prop="stock" label="库存" :label-width="formLabelWidth">
          <el-input type="number" v-model="goodsForm.stock" autocomplete="off" placeholder="请输入亏存，-1为不限量" />
        </el-form-item>
        <el-form-item label="商品图片" required :label-width="formLabelWidth">
          <el-upload
            class="upload-demo"
            action="https://xyx.xintujing.online:8000/api/upload"
            :on-remove="handleRemove"
            :before-remove="beforeRemove"
            multiple
            list-type="picture-card"
            :limit="3"
            :on-exceed="handleExceed"
            :on-success="handleSuccess"
            :file-list="fileList"
            :headers="{
              Authorization: 'Bearer ' + token
            }"
          >
            <el-icon><Plus /></el-icon>
            <template #tip>
              <div class="el-upload__tip">
                只能上传jpg/png文件，且不超过500kb
              </div>
            </template>
          </el-upload>
        </el-form-item>

        <!-- addressImg -->
        <el-form-item label="地址图片" required :label-width="formLabelWidth">
          <el-upload
            class="upload-demo"
            action="https://xyx.xintujing.online:8000/api/upload"
            :on-remove="handleRemove1"
            :before-remove="beforeRemove1"
            multiple
            list-type="picture-card"
            :limit="3"
            :on-exceed="handleExceed1"
            :on-success="handleSuccess1"
            :file-list="fileList1"
            :headers="{
              Authorization: 'Bearer ' + token
            }"
          >
            <el-icon><Plus /></el-icon>
            <template #tip>
              <div class="el-upload__tip">
                只能上传jpg/png文件，且不超过500kb
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">关闭</el-button>
          <el-button type="primary" @click="submitForm(ruleFormRef)">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog style="width: 30vw;" :close-on-click-modal="false" v-model="dialogFormVisibleStage" :title="dialogTypStag=='add'?'新增期':'编辑期'">
      <el-form ref="ruleFormRefStag" :model="goodsFormStag" :rules="rules">
        <el-form-item prop="startTime" label="拼团开始时间" :label-width="formLabelWidth">
          <el-date-picker v-model="goodsFormStag.startTime" value-format="YYYY-MM-DD HH:mm:ss" type="datetime" placeholder="请选择拼团开始时间" />
        </el-form-item>
        <el-form-item prop="endTime" label="拼团结束时间" :label-width="formLabelWidth">
          <el-date-picker v-model="goodsFormStag.endTime" value-format="YYYY-MM-DD HH:mm:ss" type="datetime" placeholder="请选择拼团结束时间" />
        </el-form-item>
        <el-form-item prop="pickupStartTime" label="取货开始时间" :label-width="formLabelWidth">
          <el-date-picker v-model="goodsFormStag.pickupStartTime" value-format="YYYY-MM-DD HH:mm:ss" type="datetime" placeholder="请选择拼团开始时间" />
        </el-form-item>
        <el-form-item prop="pickupEndTime" label="取货结束时间" :label-width="formLabelWidth">
          <el-date-picker v-model="goodsFormStag.pickupEndTime" value-format="YYYY-MM-DD HH:mm:ss" type="datetime" placeholder="请选择拼团开始时间" />
        </el-form-item>
        <!-- <el-form-item prop="pickupTime" label="取货时间" :label-width="formLabelWidth">
          <el-date-picker v-model="goodsFormStag.pickupTime" start-placeholder="开始时间"
        end-placeholder="结束时间" value-format="YYYY-MM-DD HH:mm:ss" type="datetimerange" placeholder="请选择取货时间" />
        </el-form-item> -->
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisibleStage = false">关闭</el-button>
          <el-button type="primary" @click="submitFormStag(ruleFormRefStag)">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { getPtGoodsList,addPtGoods,editPtGoods,editPtGoodsStag,addPtGoodsStag } from '@/api/home.js'
import { ElMessage,ElMessageBox } from 'element-plus'
import { onMounted, reactive, ref, computed } from "vue";
const props = defineProps({
  dataList: {
    type: Array,
    default: [],
  },
});
const token = computed(() => {
  return JSON.parse(localStorage.getItem('yxUserInfo')).token || ""
})
const goodsParams = ref({});
const ruleFormRef = ref();
const ruleFormRefStag = ref();

const fileList = ref([]);
const fileList1 = ref([]);
const dialogFormVisible = ref(false);
const dialogFormVisibleStage = ref(false);

const dialogType = ref('add');
const dialogTypStag = ref('add');

const formLabelWidth = '120px';
const goodsForm = reactive({});
const goodsFormStag = reactive({});
const rules = reactive({
  title: [
    { required: true, message: '请输入拼团商品名称', trigger: 'blur' },
  ],
  originalPrice: [
    { required: true, message: '请输入原价', trigger: 'blur' },
  ],
  price: [
    { required: true, message: '请输入拼团价格', trigger: 'blur' },
  ],
  startTime: [
    { required: true, message: '请选择开始时间', trigger: 'blur' },
  ],
  endTime: [
    { required: true, message: '请选择结束时间', trigger: 'blur' },
  ],
  pickupStartTime: [
    { required: true, message: '请选择取货开始时间', trigger: 'blur' },
  ],
  pickupEndTime: [
    { required: true, message: '请选择取货结束时间', trigger: 'blur' },
  ],
  listed: [
    { required: true, message: '请选择是否上架', trigger: 'blur' }
  ],
  targetCount: [
    { required: true, message: '请输入拼团人数', trigger: 'blur' }
  ],
  address: [
    { required: true, message: '请输入取货地址', trigger: 'blur' }
  ],
  stock:[
    { required: true, message: '请输入库存', trigger: 'blur' }
  ]
});
const handleRemove = (file, files) => {
  fileList.value = []
  fileList.value.push(...files)
};
const handleExceed = (files, fileList) => {
  ElMessage.error(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${
    files.length + fileList.length
  } 个文件`)
};
const beforeRemove = (file, fileList) => {
  return ElMessageBox.confirm(`确定移除 ${file.name}？`).then(() => true).catch(() => false)
};
const handleSuccess = (file,files) => { 
  fileList.value.push(files)
}

const handleRemove1 = (file, files) => {
  fileList1.value = []
  fileList1.value.push(...files)
};
const handleExceed1 = (files, fileList) => {
  ElMessage.error(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${
    files.length + fileList.length
  } 个文件`)
};
const beforeRemove1 = (file, fileList) => {
  return ElMessageBox.confirm(`确定移除 ${file.name}？`).then(() => true).catch(() => false)
};
const handleSuccess1 = (file,files) => { 
  fileList1.value.push(files)
}

const goodsList = computed(() => {
  return props.dataList;
});
const getSearch = async () => {
  goodsList.value.length = 0
  const res = await getPtGoodsList(goodsParams.value)
  if (res.code==0) {
    res.data.forEach(item=>{
      if (item.group.imgs) {
        item.group.imgList = item.group.imgs.split(',')
      }else{
        item.group.imgList = []
      }
      if (item.group.addressImg) {
        item.group.addressImgList = item.group.addressImg.split(',')
      }else{
        item.group.addressImgList = []
      }
    })
    goodsList.value.push(...res.data)
  }
};
const submitFormStag = async (formEl) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      let params = JSON.parse(JSON.stringify(goodsFormStag))
      params.pickupTime = params.pickupStartTime + '~' + params.pickupEndTime
      delete params.pickupStartTime
      delete params.pickupEndTime
      if (dialogTypStag.value == 'add') {
        addPtGoodsStag(params).then(res=>{
          if (res.code==0) {
            ElMessage.success('添加成功')
            dialogFormVisibleStage.value = false
            getSearch()
          }else{
            ElMessage.error(res.message)
          }
        })
      } else {
        editPtGoodsStag(params).then(res=>{
          if (res.code==0) {
            ElMessage.success('修改成功')
            dialogFormVisibleStage.value = false
            getSearch()
          }else{
            ElMessage.error(res.message)
          }
        })
      }
    } else {
      console.log('error submit!', fields);
    }
  });
};
const submitForm = async (formEl) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      if (fileList.value.length==0) {
        ElMessage.error('请上传商品图片')
        return
      }
      goodsForm.imgs = fileList.value.map(item=>item.response.data).join(',')
      if (fileList1.value.length==0) {
        ElMessage.error('请上传取餐地址图片')
        return
      }
      goodsForm.addressImg = fileList1.value.map(item=>item.response.data).join(',')
      console.log(231,goodsForm);
      if (dialogType.value == 'add') {
        addPtGoods(goodsForm).then(res=>{
          if (res.code==0) {
            ElMessage.success('添加成功')
            dialogFormVisible.value = false
            getSearch()
          }else{
            ElMessage.error(res.message)
          }
        })
      } else {
        editPtGoods(goodsForm).then(res=>{
          if (res.code==0) {
            ElMessage.success('修改成功')
            dialogFormVisible.value = false
            getSearch()
          }else{
            ElMessage.error(res.message)
          }
        })
      }
    } else {
      console.log('error submit!', fields);
    }
  });
};
const addFnStag = (row) => {
  dialogFormVisibleStage.value = true;
  dialogTypStag.value = 'add';
  goodsFormStag.startTime = ""
  goodsFormStag.endTime = ""
  goodsFormStag.pickupStartTime = ""
  goodsFormStag.pickupEndTime = ""
  goodsFormStag.groupId = row.group.groupId
};
const editFnStag = (row) => {
  console.log('editFn',row);
  dialogFormVisibleStage.value = true;
  dialogTypStag.value = 'edit';
  Object.assign(goodsFormStag,row)
  goodsFormStag.pickupStartTime = row.pickupTime.split('~')[0]
  goodsFormStag.pickupEndTime = row.pickupTime.split('~')[1]

};
// addFn
const addFn = () => {
  fileList.value = [];
  fileList1.value = [];
  dialogFormVisible.value = true;
  ruleFormRef.value.resetFields();
  dialogType.value = 'add';
  goodsForm.title = ""
  goodsForm.targetCount = ""
  goodsForm.address = ""
  goodsForm.price = ""
  goodsForm.originalPrice = ""
  goodsForm.listed = "1"
  goodsForm.rank = 0
  goodsForm.stock = ""
  goodsForm.imgUrl = ""
  goodsForm.remark = ""
  goodsForm.description = ""
};
// editFn
const editFn = (row) => {
  console.log('editFn',row);
  dialogFormVisible.value = true;
  dialogType.value = 'edit';
  // row.group.pickupTime = row.group.pickupTime.split('~')
  Object.assign(goodsForm,row.group)
  fileList.value = row.group.imgList.map(item=>{
    return {
      name: item,
      url: item,
      response: {
        data: item
      }
    }
  })
  fileList1.value = row.group.addressImgList.map(item=>{
    return {
      name: item,
      url: item,
      response: {
        data: item
      }
    }
  })
};
// 上架、下架
const shelves = async (row) => {
  ElMessageBox.confirm(
    `确定${row.group.listed == '1' ? '下架' : '上架'}该商品吗?`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
  .then(async () => {
    row.group.listed = row.group.listed == '1' ? '2' : '1'
    Object.assign(goodsForm,row.group)
    fileList.value = row.group.imgList.map(item=>{
      return {
        name: item,
        url: item,
        response: {
          data: item
        }
      }
    })
    editPtGoods(goodsForm).then(res=>{
      if (res.code==0) {
        ElMessage.success('修改成功')
      }
    })
  })
};

onMounted(() => {
  console.log(props);
});

const previewImage = (url) => {};
</script>

<style lang="less" scoped>
.content{
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
}
.imgs {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  img {
    margin-right: 10px;
  }
}
.table{
  flex: 1;
  overflow-y: auto;
}
.orderTable{
  :deep(tbody) tr:hover>td {
    background: none;
  }
  :deep(.el-table__row){
    background: #EEF5FE;
  }
  :deep(.expandTable) .el-table__row{
    background: #FFFFFF;
  }
  .stage—search{
    width: 100%;
    padding: 10px;
    box-sizing: border-box;
  }
}
</style>